<template>
  <div class="teacher-profile">
    <div class="page-header">
      <h2>个人中心</h2>
    </div>

    <!-- 个人信息卡片 -->
    <el-card class="profile-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
          <el-button type="primary" @click="handleEditProfile">
            <el-icon><Edit /></el-icon>
            编辑信息
          </el-button>
        </div>
      </template>
      
      <div class="profile-content">
        <div class="profile-avatar">
          <div class="avatar-wrapper">
            <el-avatar :size="140" :src="avatarUrl || userInfo.avatar" class="avatar">
              <el-icon><User /></el-icon>
            </el-avatar>
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-change="handleAvatarChange"
              :auto-upload="false"
              accept="image/*"
            >
              <div class="upload-overlay">
                <el-icon class="upload-icon"><Camera /></el-icon>
                <span class="upload-text">更换头像</span>
              </div>
            </el-upload>
          </div>
        </div>
        
        <div class="profile-info">
          <el-descriptions :column="2" border>
            <el-descriptions-item label="工号">
              {{ userInfo.teNo || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              {{ userInfo.teName || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ userInfo.teSex === 1 ? '男' : userInfo.teSex === 0 ? '女' : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="身份证号">
              {{ userInfo.teIdCard || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="手机号">
              {{ userInfo.tePhone || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="邮箱">
              {{ userInfo.teEmail || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="QQ">
              {{ userInfo.teQq || '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="备注" :span="2">
              {{ userInfo.teRemark || '暂无备注' }}
            </el-descriptions-item>
            <el-descriptions-item label="更新时间" :span="2">
              {{ formatDate(userInfo.teUpdateDate) }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>

    <!-- 编辑个人信息对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑个人信息"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="editForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="姓名" prop="teName">
          <el-input v-model="editForm.teName" placeholder="请输入姓名" />
        </el-form-item>
        
        <el-form-item label="性别" prop="teSex">
          <el-select v-model="editForm.teSex" placeholder="请选择性别" style="width: 100%">
            <el-option label="男" :value="1" />
            <el-option label="女" :value="0" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="身份证号" prop="teIdCard">
          <el-input v-model="editForm.teIdCard" placeholder="请输入身份证号" />
        </el-form-item>
        
        <el-form-item label="手机号" prop="tePhone">
          <el-input v-model="editForm.tePhone" placeholder="请输入手机号" />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="teEmail">
          <el-input v-model="editForm.teEmail" placeholder="请输入邮箱" />
        </el-form-item>
        
        <el-form-item label="QQ" prop="teQq">
          <el-input v-model="editForm.teQq" placeholder="请输入QQ号" />
        </el-form-item>
        
        <el-form-item label="备注" prop="teRemark">
          <el-input 
            v-model="editForm.teRemark" 
            type="textarea" 
            :rows="4"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Edit, User, Camera } from '@element-plus/icons-vue'
import { getTeacherInfo, updateTeacherInfo } from '../api/teacherUser'

// 用户信息
const userInfo = ref({})
const avatarUrl = ref('')

// 编辑对话框
const editDialogVisible = ref(false)

// 编辑表单
const editForm = reactive({
  teacherId: null,
  teName: '',
  teSex: '',
  teIdCard: '',
  tePhone: '',
  teEmail: '',
  teQq: '',
  teRemark: ''
})

// 表单验证规则
const rules = {
  teName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  teSex: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  tePhone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  teEmail: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const formRef = ref()

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    if (user.teacherId) {
      const response = await getTeacherInfo(user.teacherId)
      if (response.data) {
        userInfo.value = response.data
      } else {
        // 如果接口失败，使用本地存储的用户信息
        userInfo.value = user
      }
    } else {
      userInfo.value = user
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    // 使用本地存储的用户信息作为备选
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    userInfo.value = user
  }
}

// 编辑个人信息
const handleEditProfile = () => {
  // 填充表单数据
  Object.keys(editForm).forEach(key => {
    if (key === 'teacherId') {
      editForm[key] = userInfo.value.teacherId || userInfo.value.id
    } else {
      editForm[key] = userInfo.value[key] || ''
    }
  })
  editDialogVisible.value = true
}

// 提交编辑
const handleSubmit = async () => {
  const valid = await formRef.value.validate()
  if (valid) {
    try {
      await updateTeacherInfo(editForm)
      ElMessage.success('更新成功')
      editDialogVisible.value = false
      // 重新获取用户信息
      await fetchUserInfo()
    } catch (error) {
      console.error('更新失败:', error)
      ElMessage.error('更新失败，请重试')
    }
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit', 
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit' 
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 处理头像上传
const handleAvatarChange = (file) => {
  const isImage = file.raw.type.startsWith('image/')
  const isLt2M = file.raw.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return
  }

  // 预览图片
  const reader = new FileReader()
  reader.onload = (e) => {
    avatarUrl.value = e.target.result
    ElMessage.success('头像已更新（注意：需要点击"编辑信息"并保存才能永久保存）')
  }
  reader.readAsDataURL(file.raw)
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.teacher-profile {
  background: #f5f7fa;
  padding: 32px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 28px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1.5px;
}

.profile-card {
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
  transition: all 0.3s ease;
  max-width: 1200px;
  margin: 0 auto;
}

.profile-card:hover {
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.profile-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-bottom: none;
  padding: 20px 24px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #ffffff;
  font-weight: 600;
  font-size: 20px;
}

.card-header .el-button {
  border-radius: 6px;
  font-weight: 500;
  padding: 8px 20px;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.95);
  border: none;
  color: #667eea;
}

.card-header .el-button:hover {
  background: #ffffff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.profile-content {
  padding: 32px;
  display: flex;
  gap: 32px;
  align-items: flex-start;
}

.profile-avatar {
  flex-shrink: 0;
  text-align: center;
  padding: 20px;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  border-radius: 16px;
}

.avatar-wrapper {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.avatar-wrapper:hover .upload-overlay {
  opacity: 1;
}

.avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #ffffff;
  font-size: 52px;
  border: 4px solid #ffffff;
  box-shadow: 0 4px 16px rgba(102, 126, 234, 0.3);
  width: 140px;
  height: 140px;
}

.avatar-uploader {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  overflow: hidden;
}

.upload-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s;
  cursor: pointer;
}

.upload-icon {
  font-size: 32px;
  color: white;
  margin-bottom: 8px;
}

.upload-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

.profile-info {
  flex: 1;
}

.profile-info :deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.profile-info :deep(.el-descriptions-item) {
  transition: background 0.2s ease;
}

.profile-info :deep(.el-descriptions-item:hover) {
  background: rgba(102, 126, 234, 0.02);
}

.profile-info :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.profile-info :deep(.el-descriptions__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.profile-info :deep(.el-descriptions__body) {
  background: #ffffff;
}

.profile-info :deep(.el-descriptions-item__label) {
  background: linear-gradient(135deg, #f5f7fa 0%, #e8ecf1 100%);
  color: #606266;
  font-weight: 600;
  width: 120px;
  padding: 14px 16px;
  font-size: 15px;
}

.profile-info :deep(.el-descriptions-item__content) {
  color: #2c3e50;
  padding: 14px 20px;
  font-size: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding-top: 20px;
}

.dialog-footer .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 12px 28px;
  font-size: 15px;
  transition: all 0.3s ease;
}

.dialog-footer .el-button--primary {
  background: #409eff;
  border-color: #409eff;
}

.dialog-footer .el-button--primary:hover {
  background: #66b1ff;
  border-color: #66b1ff;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-dialog__body) {
  padding: 28px 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 0 0 8px 8px;
  border-top: 1px solid #ebeef5;
}

/* 表单样式优化 */
:deep(.el-form-item__label) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 15px;
  padding-bottom: 8px;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s ease;
  padding: 6px 12px;
  font-size: 15px;
}

:deep(.el-input__wrapper:hover) {
  border-color: #409eff;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

/* 响应式设计 */
@media (max-width: 992px) {
  .profile-content {
    flex-direction: column;
    gap: 20px;
    align-items: center;
  }
  
  .profile-avatar {
    width: 100%;
    display: flex;
    justify-content: center;
  }
}

@media (max-width: 768px) {
  .teacher-profile {
    padding: 16px;
  }
  
  .page-header {
    margin-bottom: 16px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .profile-content {
    padding: 16px;
    gap: 16px;
  }
  
  .profile-info :deep(.el-descriptions-item__label) {
    width: 90px;
    padding: 8px 10px;
    font-size: 13px;
  }
  
  .profile-info :deep(.el-descriptions-item__content) {
    padding: 8px 12px;
    font-size: 13px;
  }
  
  .card-header span {
    font-size: 16px;
  }
  
  .card-header .el-button {
    padding: 6px 16px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .teacher-profile {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 18px;
  }
  
  .profile-card {
    border-radius: 12px;
  }
  
  .profile-card :deep(.el-card__header) {
    padding: 12px 16px;
  }
  
  .profile-content {
    padding: 12px;
  }
  
  .profile-avatar {
    padding: 12px;
  }
  
  .avatar {
    width: 100px !important;
    height: 100px !important;
    font-size: 40px;
  }
  
  .profile-info :deep(.el-descriptions-item__label) {
    width: 75px;
    padding: 6px 8px;
    font-size: 12px;
  }
  
  .profile-info :deep(.el-descriptions-item__content) {
    padding: 6px 10px;
    font-size: 12px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 8px;
  }
  
  .card-header .el-button {
    width: 100%;
  }
}
</style>


